<template>
	<u-popup :class="themeName" v-model="show" z-index="999999" mode="bottom" border-radius="14" :closeable="true"
		:safe-area-inset-bottom="true">
		<!-- Header -->
		<view class="header">
			<!-- Goods Image -->
			<u-image width="180" height="180" mode="aspectFit" border-radius="10"
				:src="goodsOptionsSpec.image || defaultInfo.image" @click="previewGoodsImage" />
			<!-- Goods Checked Specifcation -->
			<view class="header-content u-skeleton-rect">
				<!-- 砍价商品 -->
				<view v-if="isBargain">
					<view>
						{{$zhTran('最低可砍至')}}
						<price class="header-content-price"
							:content="goodsOptionsSpec.floor_price || defaultInfo.bargain_price" main-size="36rpx"
							minor-size="28rpx" :color="themeColor" :prefix="prefix" />
					</view>
					<view class="muted sm">
						{{$zhTran('原价')}}
						<price class="header-content-price" :content="goodsOptionsSpec[priceKey] || defaultInfo.price"
							main-size="28rpx" minor-size="28rpx" color="#999" :prefix="prefix" />
					</view>
				</view>

				<view class="flex" v-else>
					<!-- 售价 -->
					<block v-if="defaultInfo.show_goods_price == 1">
						<block v-if="defaultInfo.show_price_type==1 && goodsOptionsSpec.member_price && isLogin">
							<price class="header-content-price" :content="goodsOptionsSpec.member_price"
								main-size="46rpx" minor-size="32rpx" :color="themeColor" :prefix="prefix" />
						</block>
						<block v-else>
							<price class="header-content-price"
								:content="goodsOptionsSpec[priceKey] || defaultInfo.price" main-size="46rpx"
								minor-size="32rpx" :color="themeColor" :prefix="prefix" />
							<!-- 普通商品会员价 用户有登陆且且该商品有设置会员价才显示 -->
							<view class="vip-price flex m-b-20 m-l-10"
								v-if="goodsOptionsSpec.member_price && isLogin && defaultInfo.show_user_price==1">
								<view class="price-name xxs">{{$zhTran('会员价')}}</view>
								<view style="padding: 0 10rpx">
									<price :content="goodsOptionsSpec.member_price" :weight="500" color="#7B3200"
										:prefix="prefix">
									</price>
								</view>
							</view>
						</block>
					</block>
				</view>

				<!-- 库存 -->
				<view class="header-content-label" v-if="defaultInfo.show_stock == 1">{{$zhTran('库存')}}：
					<text v-if="goodsOptionsSpec.stock == 0">{{$zhTran(stock_zero_desc)}}</text>
					<text
						v-else>{{ goodsOptionsSpec.stock_desc ||  defaultInfo.stock_desc}}{{ Number(goodsOptionsSpec.stock_desc ||  defaultInfo.stock_desc)?  (defaultInfo.unit||'') : ''}}</text>
				</view>
			</view>
		</view>
		<!-- Main -->
		<view class="main">
			<!-- Specifcation -->
			<scroll-view scroll-y="true" class="scroll-spec">
				<view class="spec" v-for="(specItem, specIndex) in specListMap" :key="specIndex">
					<!-- Title -->
					<view class="spec-title">{{ specItem.name }}</view>
					<!-- Content -->
					<view class="spec-content">
						<view v-for="(optionItem, optionIndex) in specItem.spec_list" :key="optionIndex"
							:class="['spec-item', { 'spec-item--active': specCheckedList[specIndex].id == optionItem.id }]"
							@click="changeSpecOption(specIndex, optionItem.id)"
							v-if="specIndex==0 ||(show_ids[specIndex]!=undefined && show_ids[specIndex].indexOf(optionItem.id) > -1)">
							{{ optionItem.value }}
							<text v-if="specDisabeld(optionItem.id)">{{$zhTran('('+stock_zero_desc+')')}}</text>
						</view>
					</view>
				</view>
				<view class="spec" v-if="auxArrShow">
					<view class="spec-title">{{$zhTran('其他单位')}}</view>
					<view class="spec-content">
						<view v-for="item,idx in auxArr" :key="idx"
							:class="['spec-item', { 'spec-item--active': auxId == item.id }]"
							@click="changeUnitOption(item.id)">
							{{ item.aux_name }}{{item.coefficient!=''?'('+item.coefficient+item.base_name+')':''}}
						</view>
					</view>
				</view>
			</scroll-view>

			<!-- Goods Number -->
			<view class="total" v-if="defaultInfo.show_goods_buycount == 1">
				<view class="total-label">{{$zhTran('数量')}}</view>
				<u-number-box v-model="goodsTotal" :min="1" :step="step"
					:max="understock_order_enabled?99999:goodsOptionsSpec.stock" :size="36" />
			</view>
		</view>

		<!-- operation -->
		<view class="operation">
			<view class="operation-button disabled" v-if="goodsOptionsSpec.stock == 0 && !understock_order_enabled">
				{{$zhTran(stock_zero_desc)}}
			</view>
			<template v-else>
				<view class="operation-button" v-for="(item, index) in buttons" :key="index" :style="[item.style]"
					@click="onButtonHandle(item.event)">
					{{$zhTran(item.text)}}
				</view>
			</template>
		</view>
	</u-popup>

</template>


<script>
	/**
	 * @description 商品规格选择Popup弹窗
	 * @property {String} mode 商品规格模式 (默认值: normal)
	 * @property {Array} specList 规格列表 (必填项)
	 * @property {Array} specMap 规格映射表 (必填项)
	 * @property {Array} buttons 按钮组 (默认: [{ text: '立即购买', style: {}, event: 'buy' }])
	 * @event {Function} [event] 点击按钮 (事件名由按钮组的event提供) 
	 * @example <goods-spec v-model="show" @buy="handleSubmit" />
	 */

	import {
		apiGoodsDetail
	} from '@/api/goods'
	import {
		mapGetters,
	} from 'vuex'

	export default {
		name: 'GoodsSpec',

		props: {
			// 显示状态
			value: {
				type: Boolean,
				default: false,
			},

			// 商品规格模式
			mode: {
				type: String,
				default: 'normal'
			},

			// 按钮组
			buttons: {
				type: Array,
				default: () => [{
					text: '立即购买',
					style: {},
					event: 'buy',
				}]
			},

			// 规格列表
			specList: {
				type: Array,
				default: () => [],
			},

			// 规格映射表
			specMap: {
				type: Array,
				default: () => [],
			},
			// 价格字段名
			priceKey: {
				type: String,
				default: 'sell_price'
			},
			// 默认商品信息
			defaultInfo: {
				type: Object,
				default: () => ({}),
			},
			isBargain: {
				type: Boolean,
				default: false,
			},

			// 前缀
			prefix: {
				type: String,
				default: '￥'
			},
			aux_def_id: {
				type: String,
				default: ''
			},
			// 负数出库
			understock_order_enabled: {
				type: [String, Number],
				default: 0,
			},
		},

		data() {
			return {
				specMapTable: new Map(), // 规格值映射表
				specCheckedList: [], // 已选择的规格列表
				goodsTotal: 1, // 商品数量
				step: 1, //步进器步长
				goodsOptionsSpec: {}, // 商品已选择的规格
				nullSpec: [],
				auxArr: [],
				auxId: '',
				coefficient: 1,
				specListMap: [],
				show_ids: []
				// stockoutList: []
			}
		},
		created() {
			this.specListMap = this.specList

			console.log('state', this.$store.state.app.config)
		},
		computed: {
			// 弹窗Popup显示状态
			show: {
				get: function() {
					return this.value
				},
				set: function(value) {
					this.$emit('input', value)
				}
			},
			specCheckedIds() {
				return this.specCheckedList.map(item => item.id).filter(item => item).join(',')
			},
			specDisabeld() {
				return (id) => this.nullSpec.find(item => item == id)
			},
			auxArrShow() {
				return !this.auxArr ? false : this.auxArr.length > 0
			},
			stock_unzero_desc() {
				return this.$store.state.app.config.stock_unzero_desc || ''
			},
			stock_zero_desc() {
				return this.$store.state.app.config.stock_zero_desc || '缺货'
			},

			// isLogin，判断是否显示会员价
			...mapGetters['isLogin'],
		},

		methods: {
			// 选择规格
			changeSpecOption(index, value) {
				const {
					id
				} = this.specCheckedList[index]
				// console.log(index, value, this.specCheckedList)
				// if (id == value) {
				// 	value = ''
				// }
				this.$set(this.specCheckedList[index], 'id', value)
				// console.log('specCheckedList', this.specCheckedList)
				let check_ids = this.specCheckedList.map(item => item.id)
				// console.log('check_ids', check_ids)
				let show_ids = [],
					show_spec = this.specMap.filter(item => item.sku_show),
					sku_value = show_spec
				// console.log('show_spec', show_spec)
				for (var i in check_ids) {
					if (show_ids[i] == undefined) show_ids[i] = []
				}
				for (var i = 0; i < check_ids.length - 1; i++) {
					let sku_idx = check_ids[i],
						sku_arr = []
					// console.log('sku_idx', sku_idx, i)
					sku_value.forEach((item) => {
						let arr = item.spec_value_ids.split(',')
						if (i == 0) {
							if (sku_idx == Number(arr[i]))
								sku_arr.push(item)
						} else {
							sku_arr.push(item)
						}
					})
					// console.log('sku_arr', sku_arr)
					sku_value = sku_arr
				}
				if (index == 0) {
					let arr = sku_value[0].spec_value_ids.split(',')
					if (arr.length > 1) {
						for (var i in arr) {
							this.$set(this.specCheckedList[i], 'id', arr[i])
						}
					}
					check_ids = this.specCheckedList.map(item => item.id)
				}
				// console.log('sku_value', sku_value)
				if (sku_value.length > 0) {
					let next_sku_id = ''
					sku_value.forEach(item => {
						let arr = item.spec_value_ids.split(',')
						for (var i in arr) {
							// console.log('i', i, (arr.length - 1))
							// console.log('value', value, arr[i - 1], arr[i])
							if (i != arr.length - 1 || check_ids[i - 1] == arr[i - 1]) {
								if (show_ids[i].indexOf(Number(arr[i])) == -1)
									show_ids[i].push(Number(arr[i]))

								if (value == arr[i - 1] && i > 0) {
									if (next_sku_id == '') next_sku_id = arr[i]
									if (this.specCheckedList[index + 1] != undefined)
										this.$set(this.specCheckedList[index + 1], 'id', next_sku_id)
								}
							}
						}
					})
				}
				// console.log('specCheckedList', this.specCheckedList)
				this.show_ids = show_ids
			},
			// 选择辅助单位
			changeUnitOption(value) {
				if (!this.auxArr || this.auxArr == undefined) {
					this.handelLimitBuy()
					return
				}

				let unit_arr = this.auxArr.filter(item => {
					return item.id == value
				})

				if (unit_arr.length > 0) {
					this.goodsOptionsSpec.sell_price = unit_arr[0].unit_price
					this.coefficient = unit_arr[0].coefficient || 1
				}
				this.auxId = value
				this.handelLimitBuy()
			},
			handelLimitBuy() {
				let limit_package = Number(this.goodsOptionsSpec.limit_package) || 0
				if (limit_package > 0) {
					let diff = limit_package % this.coefficient
					if (diff > 0) {
						this.step = (limit_package - diff) / this.coefficient + 1
						this.goodsTotal = (limit_package - diff) / this.coefficient + 1
					} else {
						this.step = limit_package / this.coefficient
						this.goodsTotal = limit_package / this.coefficient
					}
				} else {
					this.step = 1
					this.goodsTotal = 1
				}
			},

			// 点击按钮
			onButtonHandle(event) {
				const nullSelect = this.specCheckedList.find(item => !item.id)
				if (nullSelect) {
					this.$toast({
						title: `${this.$zhTran('请选择')+nullSelect.name}`
					})
					return
				}
				this.show = false
				this.throwSpecEmit(event)
			},

			// 抛出事件
			throwSpecEmit(name) {
				this.$emit(name, {
					spec: this.goodsOptionsSpec,
					number: this.goodsTotal,
					aux_id: this.auxId,
				})
			},

			// 查看商品图片
			previewGoodsImage() {
				const image = this.goodsOptionsSpec.image || this.defaultInfo.image
				uni.previewImage({
					urls: [image],
				})
			},
			checkStock() {
				let nullStock = this.specMap.filter((item) => item.stock == 0)
				this.nullSpec = nullStock.reduce((prev, item) => {
					const idsArr = item.spec_value_ids.split(',')
					const checkIdsArr = this.specCheckedIds.split(',')
					const includesIds = idsArr.filter((item) => this.specCheckedIds.includes(item))
					if (!this.specCheckedIds) return prev
					// 全选
					if (item.spec_value_ids == this.specCheckedIds) {
						return prev.concat(...checkIdsArr)
					}
					// 剩下一个未选
					if (includesIds.length && includesIds.length == this.specCheckedList.length - 1) {
						return prev.concat(idsArr.filter((item) => !this.specCheckedIds
							.includes(item)))
					}

					return prev
				}, [])
				// console.log(this.nullSpec)
			}
		},


		watch: {
			// 变更规格
			specCheckedList: {
				handler(value) {
					const selectSepc = this.specMapTable.get(this.specCheckedIds)
					this.checkStock()
					if (selectSepc) {
						this.goodsOptionsSpec = selectSepc
						this.auxArr = selectSepc.aux_arr
					} else {
						this.goodsOptionsSpec = {}
						this.auxArr = []
					}
					this.changeUnitOption(this.defaultInfo?.aux_def_id)
					this.throwSpecEmit('change')
				},
				deep: true,

			},
			// 初始化规格映射表
			specMap: {
				handler(value) {
					// 配置隐射关系spec_value_ids => self
					value.map(item => this.specMapTable.set(item.spec_value_ids, item))
					value = value.filter(item => item.sku_show == 1)
					const checkItem = value.find((item) => item.stock)
					const checkItemIds = checkItem ? checkItem.spec_value_ids.split(',') : ''

					//初始化选中数据
					this.specCheckedList = this.specList.map((item, index) => ({
						name: item.name,
						id: checkItemIds[index] || item.spec_list[0].id,
					}))

					// console.log('specCheckedList', this.specCheckedList)
					let check_ids = this.specCheckedList.map(item => item.id)
					// console.log('check_ids', check_ids)
					// console.log('value', value)
					let show_ids = [],
						sku_value = value
					for (var i in check_ids) {
						if (show_ids[i] == undefined) show_ids[i] = []
					}
					for (var i = 0; i < check_ids.length - 1; i++) {
						let sku_idx = check_ids[i],
							sku_arr = []
						// console.log('sku_idx', sku_idx, i)
						sku_value.forEach((item) => {
							let arr = item.spec_value_ids.split(',')
							if (i == 0) {
								if (sku_idx == Number(arr[i]))
									sku_arr.push(item)
							} else {
								sku_arr.push(item)
							}
						})
						// console.log('sku_arr', sku_arr)
						sku_value = sku_arr
					}
					// console.log('sku_value', sku_value)
					if (sku_value.length > 0) {
						sku_value.forEach(item => {
							let arr = item.spec_value_ids.split(',')
							for (var i in arr) {
								if (i != arr.length - 1 || check_ids[i - 1] == arr[i - 1])
									if (show_ids[i].indexOf(Number(arr[i])) == -1)
										show_ids[i].push(Number(arr[i]))
							}
						})
					}
					this.show_ids = show_ids
					// console.log('show_ids', show_ids)

					this.auxArr = checkItem != undefined && checkItem.aux_arr != undefined ? checkItem.aux_arr : []
				},
				immediate: true
			},
		},
	}
</script>


<style lang="scss" scoped>
	.header {
		display: flex;
		padding: 20rpx;

		&-content {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: center;
			margin-left: 20rpx;

			&-label {
				padding-top: 10rpx;
				font-size: $-font-size-sm;
			}

			&-price {
				margin-bottom: 20rpx;
			}

			// 会员价
			.vip-price {
				margin-top: 5rpx;
				background-color: #FFE9BA;
				color: #FFD4B7;
				line-height: 36rpx;
				border-radius: 6rpx;
				overflow: hidden;

				.price-name {
					background-color: #101010;
					padding: 3rpx 12rpx;
					position: relative;
					overflow: hidden;

					&::after {
						content: '';
						display: block;
						width: 20rpx;
						height: 20rpx;
						position: absolute;
						right: -15rpx;
						background-color: #FFE9BA;
						border-radius: 50%;
						top: 50%;
						transform: translateY(-50%);
						box-sizing: border-box;
					}
				}
			}
		}
	}


	.main {
		padding: 20rpx;
		border-top: $-solid-border;

		.scroll-spec {
			min-height: 320rpx;
			max-height: 600rpx;
		}

		.spec {
			padding: 10rpx 0;

			&-title {
				font-size: $-font-size-nr;
			}

			&-content {
				display: flex;
				flex-wrap: wrap;
				padding-top: 20rpx;
			}

			&-item {
				display: flex;
				align-items: center;
				justify-content: center;
				min-width: 100rpx;
				box-sizing: border-box;
				padding: 8rpx 25rpx;
				margin: 0 20rpx 20rpx 0;
				border-radius: 60px;
				font-size: $-font-size-sm;
				background-color: #F4F4F4;

				&--active {
					@include font_color();
					@include box_shadow(0, 0, 0, 1px);
					@include background_color(0.2);
				}

				// &--disabeld {
				// 	position: relative;
				// 	@include font_color();
				// 	@include box_shadow(0, 0, 0, 1px);
				// 	@include background_color(0.2);

				// 	&::after {
				// 		position: absolute;
				// 		top: -1em;
				// 		right: -0.5em;
				// 		content: "缺货";
				// 		display: block;
				// 		padding: 2rpx 4rpx;
				// 		border: solid 1px #FFFFFF;
				// 		border-radius: 2px;
				// 		font-size: $-font-size-xxs;
				// 		@include background_color();
				// 		color: #FFFFFF;
				// 	}
				// }
			}
		}

		.total {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 0;

			&-label {
				font-size: $-font-size-nr;
			}
		}
	}


	.operation {
		display: flex;
		justify-content: space-between;
		padding: 10rpx 20rpx;

		&-button {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 82rpx;
			border-radius: 60px;
			font-size: $-font-size-md;
			color: #FFFFFF;

			@include background_color() &:nth-child(n+2) {
				margin-left: 20rpx;
			}

			&.disabled {
				background-color: #D7D7D7;
			}
		}
	}
</style>